<template>
  <div class="role-container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <span>角色管理 /</span>
    </div>

    <!-- 操作按钮区域 -->
    <div class="operation-area">
      <el-button type="primary" @click="showAddDialog">+ 添加角色</el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="角色名称：">
          <el-input v-model="searchForm.name" placeholder="请输入角色名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="角色标识：">
          <el-input v-model="searchForm.label" placeholder="请输入角色标识" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table :data="roleList" stripe style="width: 100%" v-loading="isLoading">
        <el-table-column label="序号" width="80" align="center">
          <template #default="scope">
            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="角色名称" align="center"></el-table-column>
        <el-table-column prop="label" label="角色标识" align="center"></el-table-column>
        <el-table-column prop="updateTime" label="最后修改时间" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template #default="scope">
            <el-button type="text" @click="showEditDialog(scope.row)">修改</el-button>
            <el-button type="text" @click="showDeleteDialog(scope.row)" style="color: #ff4d4f">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-area">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>

    <!-- 添加/编辑角色模态框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="closeDialog"
    >
      <el-form :model="formData" :rules="formRules" ref="roleForm" label-width="100px">
        <el-form-item label="角色名称：" prop="name">
          <el-input 
            v-model="formData.name" 
            placeholder="请输入角色名称" 
            maxlength="10"
            @blur="validateName"
          ></el-input>
          <div v-if="errors.name" class="error-message">{{ errors.name }}</div>
        </el-form-item>
        <el-form-item label="角色标识：" prop="label">
          <el-input 
            v-model="formData.label" 
            placeholder="请输入角色标识" 
            maxlength="20" 
            show-word-limit
            @blur="validateLabel"
          ></el-input>
          <div v-if="errors.label" class="error-message">{{ errors.label }}</div>
        </el-form-item>
        <el-form-item label="备注：" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入备注" maxlength="50" type="textarea" :rows="2"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      title="删除确认"
      v-model="deleteDialogVisible"
      width="300px"
    >
      <span>确定要删除该角色吗？</span>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { useRoleStore } from '@/stores/role'
import { computed, reactive, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'RoleView',
  setup() {
    const roleStore = useRoleStore()
    
    // 搜索表单
    const searchForm = reactive({
      name: '',
      label: ''
    })
    
    // 分页相关
    const currentPage = ref(1)
    const pageSize = ref(10)
    
    // 对话框相关
    const dialogVisible = ref(false)
    const dialogTitle = ref('添加角色')
    const formData = reactive({
      id: '',
      name: '',
      label: '',
      remark: '',
      isUsed: false
    })
    
    const roleForm = ref(null)
    
    // 错误信息
    const errors = reactive({
      name: '',
      label: ''
    })
    
    // 删除相关
    const deleteDialogVisible = ref(false)
    const deleteRow = ref(null)
    
    // 计算属性
    const roleList = computed(() => roleStore.getRoles)
    const total = computed(() => roleStore.getTotal)
    const isLoading = computed(() => roleStore.isLoading)
    
    // 表单验证规则
    const formRules = {
      name: [
        { required: true, message: '请输入角色名称', trigger: 'blur' },
        { min: 2, max: 10, message: '角色名称长度应在2-10位之间', trigger: 'blur' },
        { validator: validateNameUnique, trigger: 'blur' }
      ],
      label: [
        { required: true, message: '请输入角色标识', trigger: 'blur' },
        { min: 2, max: 20, message: '角色标识长度应在2-20位之间', trigger: 'blur' },
        { pattern: /^[a-zA-Z]+$/, message: '角色标识只能包含字母', trigger: 'blur' },
        { validator: validateLabelUnique, trigger: 'blur' }
      ],
      remark: [
        { max: 50, message: '备注长度不能超过50位', trigger: 'blur' }
      ]
    }
    
    // 验证角色名称唯一性
    function validateNameUnique(rule, value, callback) {
      if (!value) {
        callback()
        return
      }
      
      const isExist = roleList.value.some(item => {
        return item.name === value && item.id !== formData.id
      })
      
      if (isExist) {
        callback(new Error('角色名称已存在，请输入其他名称'))
      } else {
        callback()
      }
    }
    
    // 验证角色标识唯一性
    function validateLabelUnique(rule, value, callback) {
      if (!value) {
        callback()
        return
      }
      
      const isExist = roleList.value.some(item => {
        return item.label === value && item.id !== formData.id
      })
      
      if (isExist) {
        callback(new Error('角色标识已存在，请输入其他标识'))
      } else {
        callback()
      }
    }
    
    // 格式验证 - 角色名称
    function validateName() {
      errors.name = ''
      
      if (!formData.name) {
        errors.name = '请输入角色名称'
        return
      }
      
      if (formData.name.length < 2 || formData.name.length > 10) {
        errors.name = '角色名称长度应在2-10位之间'
        return
      }
      
      const isExist = roleList.value.some(item => {
        return item.name === formData.name && item.id !== formData.id
      })
      
      if (isExist) {
        errors.name = '角色名称已存在，请输入其他名称'
      }
    }
    
    // 格式验证 - 角色标识
    function validateLabel() {
      errors.label = ''
      
      if (!formData.label) {
        errors.label = '请输入角色标识'
        return
      }
      
      if (formData.label.length < 2 || formData.label.length > 20) {
        errors.label = '角色标识长度应在2-20位之间'
        return
      }
      
      if (!/^[a-zA-Z]+$/.test(formData.label)) {
        errors.label = '角色标识只能包含字母'
        return
      }
      
      const isExist = roleList.value.some(item => {
        return item.label === formData.label && item.id !== formData.id
      })
      
      if (isExist) {
        errors.label = '角色标识已存在，请输入其他标识'
      }
    }
    
    // 格式化日期时间
    function formatDateTime(dateTime) {
      if (!dateTime) return ''
      
      const date = new Date(dateTime)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    }
    
    // 加载角色列表
    async function loadRoleList() {
      const params = {
        page: currentPage.value,
        pageSize: pageSize.value,
        ...searchForm
      }
      await roleStore.loadRoleList(params)
    }
    
    // 搜索
    function search() {
      currentPage.value = 1
      loadRoleList()
    }
    
    // 重置搜索
    function resetSearch() {
      searchForm.name = ''
      searchForm.label = ''
      currentPage.value = 1
      loadRoleList()
    }
    
    // 显示添加对话框
    function showAddDialog() {
      dialogTitle.value = '添加角色'
      formData.id = ''
      formData.name = ''
      formData.label = ''
      formData.remark = ''
      formData.isUsed = false
      
      // 清空错误信息
      errors.name = ''
      errors.label = ''
      
      dialogVisible.value = true
    }
    
    // 显示编辑对话框
    function showEditDialog(row) {
      dialogTitle.value = '修改角色'
      formData.id = row.id
      formData.name = row.name
      formData.label = row.label
      formData.remark = row.remark || ''
      formData.isUsed = row.isUsed || false
      
      // 清空错误信息
      errors.name = ''
      errors.label = ''
      
      dialogVisible.value = true
    }
    
    // 关闭对话框
    function closeDialog() {
      dialogVisible.value = false
      if (roleForm.value) {
        roleForm.value.resetFields()
      }
      // 清空错误信息
      errors.name = ''
      errors.label = ''
    }
    
    // 提交表单
    async function submitForm() {
      // 先进行客户端验证
      validateName()
      validateLabel()
      
      if (errors.name || errors.label) {
        ElMessage.warning('请检查表单填写是否正确')
        return
      }
      
      try {
        let result
        if (formData.id) {
          // 编辑角色
          result = await roleStore.updateRole(formData)
          if (result.success) {
            ElMessage.success('修改成功')
          } else {
            ElMessage.error(result.message || '修改失败')
          }
        } else {
          // 添加角色
          result = await roleStore.addRole(formData)
          if (result.success) {
            ElMessage.success('添加成功')
          } else {
            ElMessage.error(result.message || '添加失败')
          }
        }
        
        if (result.success) {
          closeDialog()
        }
      } catch (error) {
        ElMessage.error('操作失败，请稍后重试')
      }
    }
    
    // 显示删除确认对话框
    function showDeleteDialog(row) {
      // 检查角色是否被使用
      if (row.isUsed) {
        ElMessage.warning(`角色"${row.name}"正在被使用，无法删除！`)
        return
      }
      
      deleteRow.value = row
      deleteDialogVisible.value = true
    }
    
    // 确认删除
    async function confirmDelete() {
      if (!deleteRow.value) return
      
      try {
        const result = await roleStore.deleteRole(deleteRow.value.id)
        if (result.success) {
          ElMessage.success('删除成功')
        } else {
          ElMessage.error(result.message || '删除失败')
        }
      } catch (error) {
        ElMessage.error('删除失败，请稍后重试')
      } finally {
        deleteDialogVisible.value = false
        deleteRow.value = null
      }
    }
    
    // 分页相关
    function handleSizeChange(size) {
      pageSize.value = size
      currentPage.value = 1
      loadRoleList()
    }
    
    function handleCurrentChange(current) {
      currentPage.value = current
      loadRoleList()
    }
    
    // 初始化加载
    onMounted(() => {
      loadRoleList()
    })
    
    return {
      searchForm,
      currentPage,
      pageSize,
      dialogVisible,
      dialogTitle,
      formData,
      roleForm,
      errors,
      deleteDialogVisible,
      deleteRow,
      roleList,
      total,
      isLoading,
      formRules,
      validateName,
      validateLabel,
      formatDateTime,
      loadRoleList,
      search,
      resetSearch,
      showAddDialog,
      showEditDialog,
      closeDialog,
      submitForm,
      showDeleteDialog,
      confirmDelete,
      handleSizeChange,
      handleCurrentChange,
      validateLabelUnique
    }
  }
}
</script>

<style scoped>
.role-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.breadcrumb {
  margin-bottom: 20px;
  font-size: 14px;
  color: #606266;
}

.operation-area {
  margin-bottom: 20px;
}

.search-area {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.search-form .el-form-item {
  margin-right: 20px;
  margin-bottom: 0;
}

.table-area {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.pagination-area {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  display: flex;
  justify-content: flex-end;
}

/* 错误提示样式 */
.error-message {
  color: #f56c6c;
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
}

/* 表格内容居中 */
.el-table .el-table__cell {
  text-align: center;
}

/* 确保按钮在小屏幕上也能正常显示 */
@media screen and (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .operation-area {
    text-align: center;
  }
}
</style>